//
//  TPBInitialize.m
//  EncryptionTPB
//
//  Created by LvJianfeng on 15/9/17.
//  Copyright © 2015年 coderjianfeng. All rights reserved.
//

#import "TPBInitialize.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "JFUtil.h"

@implementation TPBInitialize
+ (TPBInitialize *)sharedManager
{
    static TPBInitialize *sharedInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

//得到存放数据的地址(类方法)
+ (NSString *)databaseFilePath
{
    NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [filePath objectAtIndex:0];
    NSLog(@"%@",filePath);
    NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"STPB.sqlite"];
    return dbFilePath;
}

/**
 *  检查数据库是否存在
 */
- (void)checkDBExistsAtPathWithSTPB{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[self databaseFilePath]] == NO) {
        //不存在数据库文件，就去创建
        [self createSTPB];
    }
}

//得到存放数据的地址
- (NSString *)databaseFilePath
{
    NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [filePath objectAtIndex:0];
    NSLog(@"%@",filePath);
    NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"STPB.sqlite"];
    return dbFilePath;
}

/**
 *  创建数据库
 */
- (void)createSTPB{
    FMDatabase *db = [FMDatabase databaseWithPath:[self databaseFilePath]];
    if (db) {
        [db open];
        //为数据库设置缓存，提高查询效率
        [db setShouldCacheStatements:YES];
        //创建表
        [self createSTPBTable];
        [db close];
    }
}
/**
 *  创建数据表
 */
- (void)createSTPBTable{
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self databaseFilePath]];
    [queue inDatabase:^(FMDatabase *db) {
        DDDLog(@"------>创建数据表Starting...");
        
        BOOL isCreate = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS `STPB_User` (`sid` INTEGER PRIMARY KEY AUTOINCREMENT,`phone` text,`email` text,`password` text NOT NULL,`realPassword` text,`lastTime` text,`token` text);"];
        isCreate?NSLog(@"--->SUCCESS:STPB_User"):NSLog(@"--->ERROR:STPB_User");
        
        isCreate = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS `STPB_AddressBook` (`sid` INTEGER PRIMARY KEY AUTOINCREMENT,`uid` INTEGER NOT NULL,`name` text,`phone` text,`telephone` text,`organization` text,`department` text,`jobTitle` text,`email` text,`avatarUrl` text,`note` text,`country` text,`city` text,`state` text,`street` text,`zip` text,`countryCode` text);"];
        isCreate?NSLog(@"--->SUCCESS:STPB_AddressBook"):NSLog(@"--->ERROR:STPB_AddressBook");
        
        DDDLog(@"------>结束数据表End");
    }];
}
@end
